<template>
	<view class="">
		<view class="flex items-center py-[30rpx]  bg-[#fff] px-[20rpx] z-20 fixed top-[0] w-[100%]">
			<view class="relative flex items-center mr-[10rpx]">
				<image src="@/static/homeimg/yeeloaddress.png" class="w-[28rpx] h-[34rpx]" mode="aspectFit"></image>
			</view>
			<view class="text-[30rpx] text-[#1A1B1C] mr-[14rpx] whitespace-nowrap" @click="togetcity">
				{{CityName}}
			</view>
			<view class="mr-[20rpx]">
				<u-icon name="arrow-down" size="26rpx" color="#888C93" top='2'></u-icon>
			</view>
			<view class="w-[100%]">
				<view class="u-search-inner">
					<uv-input placeholder="请输入收货地址" shape="circle" clear v-model="inputserch"
						style="background-color: #F6F6F6;" border="none"
						prefixIconStyle="font-size: 44rpx;color: #909399">
						<template #prefix>
							<image src="../../static/homeimg/search.svg" class="w-[26rpx] h-[26rpx]" mode=""></image>
						</template>
					</uv-input>
				</view>
			</view>
		</view>
		<view v-if="isserch==false" class="mt-[110rpx] z-[1000]">
			<view class="pb-[120rpx]">
				<view class="bg-[#fff]">
					<view
						class="h-[87rpx] flex items-center justify-between px-[20rpx] text-[#4E4E4E] boderbotom text-[30rpx]">
						<view class="">
							当前位置：{{newaddress}}
						</view>
						<view class="flex relative top-[4rpx] text-[28rpx]" @click="resaddres">
							<view class="relative flex items-center  mr-[10rpx]">
								<image src="@/static/homeimg/location.svg" class="w-[30rpx] h-[36rpx]" mode=""></image>
							</view>
							<view class="text-[#FF8C00]">
								重新定位
							</view>
						</view>
					</view>
					<view class="" v-if="islogin">
						<view class="flex px-[20rpx] pt-[20rpx]">
							<view class="mr-[10rpx] flex items-center">
								<image src="@/static/homeimg/myaddress.svg" class="w-[34rpx] h-[31rpx]" mode=""></image>
							</view>
							<view class="text-[28rpx] text-[#010101]">
								我的收货地址
							</view>
						</view>
						<view class="h-[143rpx] flex items-center px-[20rpx]" v-for="(item,index) in mylist"
							:key="index" @click="choseaddress(item,1)">
							<view class="ml-[44rpx] w-[100%]">
								<view class="text-[#010101] text-[30rpx] font-[600]">
									{{item.address}}
								</view>
								<view class="mt-[10rpx]  text-[28rpx] text-[#777777]">
									{{item.realName}} {{item.phone}}
								</view>
								<view class="oneboder relative top-[30rpx]"
									v-if="mylist.length-1!==index && myaddreslist.length>3">
								</view>
							</view>
						</view>
						<view class="flex text-[28rpx] text-[#999999] ml-[44rpx] pb-[20rpx] px-[20rpx]"
							v-if="myaddreslist.length>3" @click="ishomyaddreslist=!ishomyaddreslist">
							<view class="">
								{{ishomyaddreslist?'收起全部地址':'展开更多地址'}}
							</view>
							<view class="">
								<view class="" v-if="ishomyaddreslist">
									<u-icon name="arrow-up" size="26rpx" color="#888C93" top='5'></u-icon>
								</view>
								<view class="" v-else>
									<u-icon name="arrow-down" size="26rpx" color="#888C93" top='5'></u-icon>
								</view>
							</view>
						</view>
					</view>
					<view class="">
						<view class="flex px-[20rpx] pt-[20rpx]">
							<!-- <view class="mr-[4rpx] relative right-[6rpx] flex items-center"> -->
							<view class="mr-[4rpx] relative right-[2rpx] flex items-center">
								<image src="@/static/homeimg/address.svg" class="w-[34rpx] h-[31rpx]" mode="aspectFit">
								</image>
							</view>
							<view class="text-[28rpx] text-[#010101] font-blod">
								附近地址
							</view>
						</view>
						<view class="h-[143rpx] flex items-center px-[20rpx]" v-for="(item,index) in maplist"
							:key="index" @click="choseaddress(item,2)">
							<view class="text-[28rpx] ml-[44rpx] w-[100%]">
								<view class="text-[#010101] text-[30rpx] font-[600]">
									{{item.name}}
								</view>
								<view class="mt-[10rpx] text-[#777777]">
									{{item.address}}
								</view>
								<view class="oneboder relative top-[30rpx]"
									v-if="maplist.length-1!==index && myaddreslist.length>3">
								</view>
							</view>
						</view>
						<view class="flex text-[28rpx] ml-[44rpx] text-[#999999] pb-[20rpx] px-[20rpx]"
							v-if="addreslist.length>3" @click="ismyaddreslist=!ismyaddreslist">
							<view class="">
								{{ismyaddreslist?'收起全部附近地址':'展开更多附近地址'}}
							</view>
							<view class="">
								<view class="" v-if="ismyaddreslist">
									<u-icon name="arrow-up" size="26rpx" color="#888C93" top='5'></u-icon>
								</view>
								<view class="" v-else>
									<u-icon name="arrow-down" size="26rpx" color="#888C93" top='5'></u-icon>
								</view>
							</view>
						</view>
					</view>

				</view>
			</view>
			<view class="address" @click="gotoaddress">
				<view class="flex  justify-center bg-[#fff] py-[35rpx]">
					<view class="mr-[10rpx]">
						<u-icon name="plus" size="26rpx" bold color="#FE861C" top='5'></u-icon>
					</view>
					<view class="text-[#FE861C] text-[32rpx] font-blod">
						新增收货地址
					</view>
				</view>
			</view>
		</view>
		<view class="bg-[#fff] mt-[118rpx]" v-else>
			<view class="h-[143rpx] flex items-center px-[20rpx]" v-for="(item,index) in searchlist" :key="index"
				:class="maplist.length-1==index?'':'boderbotom'" @click="choseaddress(item,2)">
				<view class="text-[28rpx]">
					<view class="text-[#010101]">
						{{item.name}}
					</view>
					<view class="mt-[16rpx] text-[#777777]">
						{{item.address}}
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		watch
	} from "vue"
	import {
		onShow,
		onLoad
	} from "@dcloudio/uni-app"
	import {
		addreses
	} from "@/api/my.js"
	import {
		useStore
	} from '@/stores/user.js'
	const store = useStore();
	import {
		storeToRefs
	} from 'pinia'
	let {
		lat,
		lng,
		addressname
	} = store;
	const latitude = ref('30.72239040798611')
	const longitude = ref('103.98227186414931')
	let latlng = "103.982271,30.722390"
	const addreslist = ref([])
	const maplist = ref([])
	const myaddreslist = ref([])
	const mylist = ref([])
	const ishomyaddreslist = ref(false)
	const ismyaddreslist = ref(false)
	watch(ishomyaddreslist, (newVal, oldVal) => {
		if (ishomyaddreslist.value == true) {
			mylist.value = myaddreslist.value
		} else {
			mylist.value = myaddreslist.value.slice(0, 3)
		}
	})
	watch(ismyaddreslist, (newVal, oldVal) => {
		if (ismyaddreslist.value == true) {
			maplist.value = addreslist.value
		} else {
			maplist.value = addreslist.value.slice(0, 3)
		}
	})
	const choseaddress = (item, type) => {
		if (type == 1) {
			console.log(item, 111111, lat, lng)
			store.addressname = item.address
			store.lat = item.lat
			store.lng = item.lng
			console.log(store, "数据仓库")
			uni.navigateBack()
		} else {
			store.addressname = item.name
			let arrs = item.location.split(',')
			store.lat = arrs[1]
			store.lng = arrs[0]
			uni.navigateBack()
		}
	}
	//搜索地址
	const inputserch = ref('')
	const isserch = ref(false)
	const searchlist = ref([])
	watch(inputserch, (newVal, oldVal) => {
		if (newVal !== '' && newVal !== null) {
			uni.request({
				url: 'https://restapi.amap.com/v5/place/text?parameters',
				data: {
					key: '87400ef66791d249381bdb0e0b33db30',
					keywords: newVal,
					city: CityName.value,
					city_limit: true,
				},
				success: function(res) {
					isserch.value = true
					searchlist.value = []
					res.data.pois.forEach((item) => {
						searchlist.value.push({
							name: item.name,
							address: item.address,
							location: item.location
						})
					})
				},
				fail: function(err) {
					console.error('获取地址列表失败', err);
				}
			});
		} else {
			setTimeout(() => {
				isserch.value = false
			}, 500)
		}
	})
	//跳转添加地址
	const gotoaddress = () => {
		if (uni.getStorageSync('loginTokenKey')) {
			uni.navigateTo({
				url: "/page_my/address/newaddress/newaddress"
			})
		} else {
			uni.navigateTo({
				url: "/pages/login/login"
			})
		}
	}
	const newaddress = ref('')
	const CityName = ref('')
	const islogin = ref(true)
	onShow(() => {
		if (uni.getStorageSync('loginTokenKey')) {
			addreses().then(res => {
				if (res.code == 200 && res.result.length > 0) {
					myaddreslist.value = res.result
					mylist.value = myaddreslist.value.slice(0, 3)
				}
			})
		} else {
			islogin.value = false
		}

		setTimeout(function() {
			uni.getStorage({
				key: 'City_Name',
				success(res) {
					CityName.value = res.data
				}
			})
		}, 500)
		wx.getSetting({
			success: (res) => {
				let authSetting = res.authSetting
				if (authSetting['scope.userLocation']) {
					if (addreslist.value.length < 1) {
						getCurrentLocation()
					}
				} else if (authSetting['scope.userLocation'] === false) {
					wx.showModal({
						title: '您未开启地理位置授权',
						content: '请在系统设置中打开位置授权，以便我们为您提供更好的服务',
						success: (res) => {
							if (res.confirm) {
								wx.openSetting()
							}
						}
					})
				} else {
					wx.authorize({
						scope: 'scope.userLocation',
						success: () => {
							getCurrentLocation()
						},
						fail: () => {
							wx.showModal({
								title: '您未开启地理位置授权',
								content: '请在系统设置中打开位置授权，以便我们为您提供更好的服务',
								success: (res) => {
									if (res.confirm) {
										wx.openSetting()
									}
								}
							})
						}
					})
				}
			}
		})
	})
	const getCurrentLocation = () => {
		uni.getLocation({
			type: 'gcj02',
			altitude: true,
			success: function(res) {
				console.log(res, "当前位置")
				let locations = `${res.longitude},${res.latitude}`;
				uni.request({
					url: 'https://restapi.amap.com/v3/geocode/regeo',
					data: {
						key: '87400ef66791d249381bdb0e0b33db30',
						location: locations,
						radius: '1000',
						extensions: 'all'
					},
					success: function(ress) {
						ress.data.regeocode.pois.forEach((item) => {
							addreslist.value.push({
								name: item.name,
								address: item.address,
								location: item.location
							})
						})
						newaddress.value = ress.data.regeocode.pois[0].name
						setTimeout(() => {
							maplist.value = addreslist.value.slice(0, 3)
						}, 300)
					},
					fail: function(err) {
						console.error('获取地址列表失败', err);
					}
				});
			},
			fail: function(err) {
				uni.showToast({
					title: "获取位置信息失败",
					icon: "none"
				})
				console.error('获取位置信息失败', err);
			}
		});
	}
	const getuserlocation = () => {
		wx.getSetting({
			success: (res) => {
				let authSetting = res.authSetting
				if (authSetting['scope.userLocation']) {
					getCurrentLocation()
				} else if (authSetting['scope.userLocation'] === false) {
					wx.showModal({
						title: '您未开启地理位置授权',
						content: '请在系统设置中打开位置授权，以便我们为您提供更好的服务',
						success: (res) => {
							if (res.confirm) {
								wx.openSetting()
							}
						}
					})
				} else {
					wx.authorize({
						scope: 'scope.userLocation',
						success: () => {
							getCurrentLocation()
						},
						fail: () => {
							wx.showModal({
								title: '您未开启地理位置授权',
								content: '请在系统设置中打开位置授权，以便我们为您提供更好的服务',
								success: (res) => {
									if (res.confirm) {
										wx.openSetting()
									}
								}
							})
						}
					})
				}
			}
		})
	}
	onLoad(() => {
		// getuserlocation()
	})
	//重新定位
	const resaddres = () => {
		uni.getLocation({
			type: 'gcj02',
			altitude: true,
			success: function(res) {
				console.log(res, "当前位置")
				let locations = `${res.longitude},${res.latitude}`;
				uni.request({
					url: 'https://restapi.amap.com/v3/geocode/regeo',
					data: {
						key: '87400ef66791d249381bdb0e0b33db30',
						location: locations,
						radius: '1000',
						extensions: 'all'
					},
					success: function(ress) {
						ress.data.regeocode.pois.forEach((item) => {
							addreslist.value.push({
								name: item.name,
								address: item.address,
								location: item.location
							})
						})
						ismyaddreslist.value = false
						newaddress.value = ress.data.regeocode.pois[0].name
						setTimeout(() => {
							maplist.value = addreslist.value.slice(0, 3)
							uni.showToast({
								title: '获取定位成功',
								icon: 'none'
							})
						}, 300)
					},
					fail: function(err) {
						console.error('获取地址列表失败', err);
					}
				});
			},
			fail: function(err) {
				uni.showToast({
					title: "获取位置信息失败",
					icon: "none"
				})
				console.error('获取位置信息失败', err);
			}
		});
	}
	const togetcity = () => {
		uni.navigateTo({
			url: "/pages/index/getcity"
		})
	}
</script>

<style scoped lang="scss">
	.address {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
	}

	.u-search-inner {
		background-color: #F6F6F6;
		padding: 5px 10px;
		border-radius: 40rpx;
	}

	.boderbotom {
		border-bottom: 1px solid #E9E9E9;
	}

	.felxsx {
		flex-direction: column;
	}

	.oneboder {
		width: 100%;
		border-bottom: 1px solid #efefef;
		transform: scaleY(.5);
	}
</style>